package com.apply.service;

import com.apply.entity.SysUser;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @author tianp
 */
@Service
public class AuthService {
    @Autowired
    private RedisService redisService;
    private static final String PREFIX = "com.regs:";
    private static final int SID_EXPIRES = 24 * 60 * 60;
    private static final int EMAIL_EXPIRES = 60;

    public String getSidKey(String key) {
        return PREFIX + key;
    }

    /**
     * 加密token
     *
     * @param sysUser
     * @return
     */
    public String sidAuthToken(SysUser sysUser) {
        Validate.notNull(sysUser);
        Validate.notEmpty(sysUser.getId().toString(), "用户信息异常");
        String sid = UUID.randomUUID().toString();
        redisService.set(getSidKey(sid), SID_EXPIRES, sysUser);
        return sid;
    }

    public SysUser getSysUserInfo(String sid) {
        return getObject(getSidKey(sid), SysUser.class);
    }

    /**
     * 每次从redis取用户的时候，增加过期时间
     *
     * @param key
     * @param type
     * @param <T>
     * @return
     */
    public <T> T getObject(String key, Class<T> type) {
        if (StringUtils.isEmpty(key)) {
            return null;
        }
        T t = redisService.get(key, type);
        if (t != null) {
            redisService.expire(key, SID_EXPIRES);
        }
        return t;
    }

    public void delete(String key) {
        redisService.del(key);
    }

    public void remove(String key, SysUser sysUser) {
        redisService.set(getSidKey(key), SID_EXPIRES, sysUser);
    }
}
